package com.nova.android.tvlauncher.ui.fragment.atv

import android.content.pm.ApplicationInfo
import android.os.Bundle
import android.view.KeyEvent
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import com.nova.android.tvlauncher.R
import com.nova.android.tvlauncher.bean.atv_bean.AppStoreDto
import com.nova.android.tvlauncher.bean.atv_bean.SearchBean
import com.nova.android.tvlauncher.databinding.FragmentSearchAtvBinding
import com.nova.android.tvlauncher.databinding.ItemAppstoreBinding
import com.nova.android.tvlauncher.databinding.ItemLocalappsBinding
import com.nova.android.tvlauncher.databinding.ItemSearchParentBinding
import com.nova.android.tvlauncher.databinding.ItemWebsiteBinding
import com.nova.android.tvlauncher.databinding.ViewSearchTopAtvBinding
import com.nova.android.tvlauncher.ext.appName
import com.nova.android.tvlauncher.ext.getAppIcon
import com.nova.android.tvlauncher.ext.getInstalledApps
import com.nova.android.tvlauncher.ext.loadGlideRadius
import com.nova.android.tvlauncher.ext.openAppInStore
import com.nova.android.tvlauncher.net.UrlManager
import io.github.lib_autorun.net.NetworkHelper
import io.github.lib_autorun.net.enum.RequestMethod
import com.lxj.xpopup.util.KeyboardUtils
import com.nova.android.tvlauncher.ui.dialog.KeyboardDialog
import com.nova.android.tvlauncher.ui.dialog.base.showDialog
import com.shudong.lib_base.ext.appContext
import com_github_lib_base.base.BaseVMFragment
import com_github_lib_base.base.BaseViewModel
import com_github_lib_base.base.GenericWebActivity
import com_github_lib_base.ext.clickNoRepeat
import com_github_lib_base.ext.openApp
import com_github_lib_base.ext.rv.addModels
import com_github_lib_base.ext.rv.models
import com_github_lib_base.ext.rv.setup
import com_github_lib_base.ext.startKtxActivity
import com_github_lib_base.ext.stringValue
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SearchATVFragment : BaseVMFragment<FragmentSearchAtvBinding, BaseViewModel>() {

    lateinit var searchBinding: ViewSearchTopAtvBinding
    override fun initView() {

        mBind.container.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS

        // 延迟执行，等系统分配完焦点后清除
        mBind.container.post {
            mBind.container.clearFocus()
            mBind.container.descendantFocusability = ViewGroup.FOCUS_AFTER_DESCENDANTS
        }

        searchBinding = mBind.viewSearchTop.searchBinding()
        mBind.rvSearch.setup(arrayListOf()) {
            addType(SearchBean.SearchBeanImpl::class, R.layout.item_search_parent)
            onBind {
                val bindingParent = getBinding<ItemSearchParentBinding>()
                val dto = data as SearchBean.SearchBeanImpl
                bindingParent.tvTitle.text = dto.title
                bindingParent.rvSearch.setup(dto.resultList) {
                    addType(SearchBean.AppStoreBean::class, R.layout.item_appstore)
                    addType(SearchBean.LocalAppBean::class, R.layout.item_localapps)
                    addType(SearchBean.WebsiteBean::class, R.layout.item_website)
                    addType(SearchBean.RecommondAppBean::class, R.layout.item_appstore)
                    onBind {
                        val tvAppName = itemView.findViewById<TextView>(R.id.tv_app_name)
                        val ivApp = itemView.findViewById<ImageView>(R.id.iv_app)
                        when (data) {
                            is SearchBean.AppStoreBean -> {
                                val binding = getBinding<ItemAppstoreBinding>()
                                binding.tvAppName.text = (data as SearchBean.AppStoreBean).appName
                                binding.ivApp.loadGlideRadius((data as SearchBean.AppStoreBean).iconUrl)
                            }

                            is SearchBean.LocalAppBean -> {
                                val binding = getBinding<ItemLocalappsBinding>()
                                binding.tvAppName.text = (data as SearchBean.LocalAppBean).appName
                                binding.ivApp.setImageDrawable((data as SearchBean.LocalAppBean).resId)
                            }

                            is SearchBean.WebsiteBean -> {
                                val binding = getBinding<ItemWebsiteBinding>()
                                //binding.tvAppName.text = (data as SearchBean.WebsiteBean).url
                                binding.ivApp.setImageResource((data as SearchBean.WebsiteBean).resId)
                            }

                            is SearchBean.RecommondAppBean -> {
                                val binding = getBinding<ItemAppstoreBinding>()
                                binding.tvAppName.text =
                                    (data as SearchBean.RecommondAppBean).appName
                                binding.ivApp.loadGlideRadius((data as SearchBean.RecommondAppBean).iconUrl)
                            }
                        }

                        itemView.setOnFocusChangeListener { view, b ->
                            if (modelPosition == 0) {
                                view.pivotX = 0f  // 将 pivotX 设置为视图的左侧
                                view.pivotY = view.height / 2f  // 将 pivotY 设置为视图的垂直中心
                            }
                            if (b) {

                                view.animate().scaleX(1.10f).scaleY(1.10f)
                                    .setDuration(200)
                                    .start()
                            } else {

                                view.animate().scaleX(1f).scaleY(1f)
                                    .setDuration(200)
                                    .start()
                            }
                        }

                        ivApp.setOnFocusChangeListener { view, b ->
                            if (modelPosition == 0) {
                                view.pivotX = 0f  // 将 pivotX 设置为视图的左侧
                                view.pivotY = view.height / 2f  // 将 pivotY 设置为视图的垂直中心
                            }
                            if (b) {

                                view.animate().scaleX(1.08f).scaleY(1.08f)
                                    .setDuration(200)
                                    .start()
                            } else {

                                view.animate().scaleX(1f).scaleY(1f)
                                    .setDuration(200)
                                    .start()
                            }
                        }

                        itemView.clickNoRepeat {
                            when (data) {
                                is SearchBean.AppStoreBean -> {
                                     (data as SearchBean.AppStoreBean).packageName.openApp()
                                }

                                is SearchBean.RecommondAppBean -> {
                                     (data as SearchBean.RecommondAppBean).packageName.openApp()
                                }

                                is SearchBean.LocalAppBean -> {
                                    (data as SearchBean.LocalAppBean).packageName.openApp()
                                }

                                is SearchBean.WebsiteBean -> {
                                    var url = (data as SearchBean.WebsiteBean).url
                                    val keyWords =
                                        mBind.viewSearchTop.searchBinding().etSearch.text.toString()
                                    when (modelPosition) {
                                        0 -> url += "${keyWords}&brand=B5"
                                        1 -> url += "/search?q=$keyWords"
                                        2 -> url += "/search?q=$keyWords"
                                        3 -> url += "/s?wd=$keyWords"
                                        4 -> url += "/search/?text=$keyWords"
                                    }
                                    startKtxActivity<GenericWebActivity>(
                                        values = arrayOf(
                                            Pair(GenericWebActivity.EXTRA_URL, url),
                                        )
                                    )
                                }
                            }
                        }

                        ivApp.clickNoRepeat {
                             (data as SearchBean.LocalAppBean).packageName.openApp()
                        }

                    }
                }
            }
        }

        searchBinding.etSearch.setOnKeyListener { view, keyCode, event ->
            if (event.action == KeyEvent.ACTION_UP) {
                //"响应了吗？？$keyCode".e("zengyue2")
            }

            false
        }

        lifecycleScope.launch {
            delay(500)
                showDialog(KeyboardDialog()){
                    bindEditText(searchBinding.etSearch)
                }
            searchBinding.etSearch.requestFocus()

        }

        searchBinding.etSearch.apply {
            onConfirmClick = {
                // KeyboardUtils.showSoftInput(mBind.etSearch)
                showDialog(KeyboardDialog()) {
                    bindEditText(searchBinding.etSearch)
                }
            }
        }

        queryRecommoondApp()
        searchBinding.etSearch.addTextChangedListener {

            debounceJob?.cancel()
            debounceJob = lifecycleScope.launch(Dispatchers.IO) {
                delay(800)

                if (it.toString().isNullOrEmpty()) {
                    // 取消上一个作业debounceJob?.cancel()
                    clearSearchResult(this)
                } else {
                    // 判断是否是回车换行
                    if (it.toString().endsWith("\n")) {
                        // 移除回车换行符
                        it?.delete(it.length - 1, it.length)
                       // KeyboardUtils.hideSoftInput(searchBinding.etSearch)

                    } else {
                        val currentText = it.toString()
                        // 只有当内容真正发生变化时才触发
                        if (currentText != previousText) {
                            previousText = currentText
                            getSearchResult(this)
                        }
                    }
                }
            }
        }

       /* searchBinding.etSearch.setOnFocusChangeListener { view, hasFocus ->

            clodseJob?.cancel()
            clodseJob = lifecycleScope.launch {
                delay(300)
                if (hasFocus && isAdded && !isDetached && !isRemoving) {
                    //KeyboardUtils.showSoftInput(searchBinding.etSearch)
                    showDialog(KeyboardDialog()){
                        bindEditText(searchBinding.etSearch)
                    }
                }
            }


        }*/
    }

    var clodseJob: Job? = null

    private var previousText: String? = null

    private fun clearSearchResult(coroutineScope: CoroutineScope) {
        coroutineScope.launch(Dispatchers.IO) {
            mBind.rvSearch.models.toMutableList().clear()
            if (recommondSearchBean != null) {
                withContext(Dispatchers.Main) {
                    mBind.rvSearch.models = listOf(recommondSearchBean) as MutableList<Any>
                }
            } else {
                queryRecommoondApp()
            }
        }
    }

    // 声明一个全局变量来持有协程作业
    private var debounceJob: Job? = null

    fun getSearchResult(coroutineScope: CoroutineScope) {
        coroutineScope.launch(Dispatchers.IO) {
            mBind.rvSearch.models.clear()
            if (recommondSearchBean != null) {
                mBind.rvSearch.addModels(listOf(recommondSearchBean!!))
            } else {
                queryRecommoondApp()
            }
            searchAppStore()
            //通过关键字匹配本地APP
            searchInstalledAppsByKeyword(this)

            withContext(Dispatchers.Main) {
                mBind.rvSearch.adapter?.notifyDataSetChanged()
            }
        }
    }

    fun queryRecommoondApp() {
        /* mViewModel.reqSearchAppList(searchBinding.etSearch.text.toString(), "81", 20).lifecycle(this, {}) {
             val recommondList = mutableListOf<SearchBean.RecommondAppBean>()
             this.appList?.forEach {
                 recommondList.add(
                     SearchBean.RecommondAppBean(
                         it?.appIcon ?: "",
                         it?.appName ?: "",
                         it?.appDownLink ?: "",
                         it?.packageName ?: ""
                     )
                 )
             }

             if (recommondList.size > 0) {
                 recommondSearchBean = SearchBean.SearchBeanImpl("推荐应用", recommondList)
                 mBind.rvSearch.addModels(listOf(recommondSearchBean) as List<Any>, index = 0)
             }
         }*/
    }

    private var recommondSearchBean: SearchBean.SearchBeanImpl? = null

    private fun searchAppStore() {
        NetworkHelper.makeRequest(
            UrlManager.SEARCH_LIST,
            RequestMethod.POST,
            mapOf(
                "userId" to 62,
                "keyword" to searchBinding.etSearch.text.toString(),
                "appColumnId" to "",
                "pageNo" to 1, "pageSize" to 10
            ),
        ) { dto: AppStoreDto?, error: Throwable? ->
            if (error == null) {
                val appstoreList = mutableListOf<SearchBean.AppStoreBean>()
                dto?.appList?.forEach {
                    appstoreList.add(
                        SearchBean.AppStoreBean(
                            it?.appIcon ?: "",
                            it?.appName ?: "",
                            it?.appDownLink ?: "",
                            it?.packageName ?: ""
                        )
                    )
                }

                if (appstoreList.isNotEmpty()) {
                    val searchBean = SearchBean.SearchBeanImpl(com.nova.lib_lang.R.string.search_txt_3.stringValue(), appstoreList)
                    if (recommondSearchBean != null) {
                       // mBind.rvSearch.addModels(listOf(searchBean), index = 1)
                    } else {
                        mBind.rvSearch.addModels(listOf(searchBean), index = 0,false)
                    }
                }

            } else {
            }
        }

    }

    private fun getSearchWebsite(coroutineScope: CoroutineScope) {
        coroutineScope.launch(Dispatchers.IO) {
            val websiteList = mutableListOf<SearchBean.WebsiteBean>()
            websiteList.add(
                SearchBean.WebsiteBean(
                    R.drawable.custom_seo,
                    "https://portal.gosrch.co/search/?search_term="
                )
            )
            websiteList.add(SearchBean.WebsiteBean(R.drawable.edge, "https://cn.bing.com"))
            websiteList.add(SearchBean.WebsiteBean(R.drawable.chrome, "https://www.google.com"))
            websiteList.add(SearchBean.WebsiteBean(R.drawable.baidu, "https://www.baidu.com"))
            websiteList.add(SearchBean.WebsiteBean(R.drawable.yandex, "https://yandex.com"))

            val searchBean = SearchBean.SearchBeanImpl(com.nova.lib_lang.R.string.search_txt_5.stringValue(), websiteList)
            withContext(Dispatchers.Main) {
                mBind.rvSearch.addModels(listOf(searchBean))
            }
        }
    }

    private fun searchInstalledAppsByKeyword(coroutineScope: CoroutineScope) {
        coroutineScope.launch(Dispatchers.IO) {
            // 获取所有已安装的应用
            val installedApps = mutableListOf<ApplicationInfo>().getInstalledApps()

            // 过滤匹配关键字的应用
            val filteredApps = installedApps.filter { appInfo ->
                // 获取应用的名称
                val appName = appInfo.loadLabel(appContext.packageManager).toString()

                // 检查应用名称是否包含关键字（忽略大小写）
                appName.contains(searchBinding.etSearch.text.toString(), ignoreCase = true)
            }
            val localAppList = mutableListOf<SearchBean.LocalAppBean>()
            filteredApps.forEach {
                localAppList.add(
                    SearchBean.LocalAppBean(
                        (it.packageName).getAppIcon(),
                        it.appName(),
                        it.packageName
                    )
                )
            }

            if (localAppList.size > 0) {
                val searchBean = SearchBean.SearchBeanImpl(com.nova.lib_lang.R.string.search_txt_4.stringValue(), localAppList)
                withContext(Dispatchers.Main) {
                    mBind.rvSearch.addModels(listOf(searchBean))
                    // 显示可用的搜索网站
                    getSearchWebsite(this)
                }
            } else {
                // 显示可用的搜索网站
                getSearchWebsite(this)
            }
        }
    }

    override fun initClick() {
        searchBinding.etSearch.apply {
            setOnEditorActionListener { v, actionId, event ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 在这里处理搜索按钮的点击事件
                    //KeyboardUtils.hideSoftInput(searchBinding.etSearch)
                    true // 返回 true 表示事件已处理
                } else {
                    false // 返回 false 继续传递事件
                }
            }
        }
    }

    companion object {
        @JvmStatic
        fun newInstance() =
            SearchATVFragment().apply {
                arguments = Bundle().apply {

                }
            }
    }

}